/**
 * @desc: 没有formItem循环渲染的上传组件方法，这里的文件渲染对象是renderImageData
 * @author: youzi
 */
export const fileOperationWithRenderImageData = {
  data() {
    return {
      renderImageData: []
    };
  },
  props: {
    initRecord: {
      type: Object,
      default: () => ({})
    }
  },
  computed: {
    filePreURL: {
      get() {
        return this.$store.state.setting.filePreURL;
      }
    }
  },
  methods: {
    /**
     * @param {object} that 组件实例that
     * @desc: 渲染文件列表
     * @author: youzi
     */
    renderImageList() {
      // debugger;
      if (!Object.keys(this.initRecord).length) {
        return;
      }
      this.renderImageData.forEach(el => {
        console.log(el);
        let key = el.dataIndex + "List";
        if (!!this.initRecord[key].length) {
          this.initRecord[key].forEach(file => {
            let tmpObj = {};
            tmpObj.uid = -(Date.now());
            tmpObj.id = Date.now();
            tmpObj.url = file;
            tmpObj.fileType = "image";
            tmpObj.name = "";
            tmpObj.status = "done";
            el.fileList.push(tmpObj);
            // let { id, absPath, fileType, fileName } = file;
            // let tmpObj = {};
            // tmpObj.uid = -id;
            // tmpObj.id = id;
            // // tmpObj.url = absPath;
            // tmpObj.url = file;
            // tmpObj.fileType = fileType;
            // tmpObj.name = fileName;
            // tmpObj.status = "done";
            // el.fileList.push(tmpObj);
          });
          // let tmpObj = {};
          // tmpObj[el.dataIndex] = el.fileList;
          // this.form.setFieldsValue(tmpObj);
        }
        console.log(this.renderImageData);
      });
    },
    /**
     * @desc: 文件校验
     * @author: youzi
     */
    handleImageValidate(rule, val, callback, title, required) {
      console.log('sssssssssssssssssss')
      console.log(rule)
      console.log(val)
      console.log(title)
      console.log(required)
      console.log('sssssssssssssssssss')
      if (!required) {
        callback();
        return;
      }
      if (val && val.fileList && val.fileList.length === 0) {
        callback(title + "不能为空");
      }
      callback();
    },
    /**
     * @desc: file-upload文件操作的函数
     * @param {string} name 对应表单字段英文名
     * @param {number} index 对应在renderImageData的第几项
     * @param {object} info 文件操作的原生对象，包含一堆文件信息
     * @author: youzi
     */
    handleImageChange(name, index, info) {
      // console.log(name, info);
      let fileList = info.fileList;
      let file = info.file;
      if (file.status === "removed") {
        this.removeImageInFE(name, index, file);
        return;
      } else {
        if (file.size > 5 * 1024 * 1024) {
          // 文件不大于5MB
          this.loading = false;
          this.$message.error("文件过大，上传失败");
          return;
        }
        this.loading = true;
        const formData = new FormData();
        var timestamp = new Date().getTime();
        const oldFileName = file.name;
        const newFileName = oldFileName.replace(".", timestamp + ".");
        const newFile = new File([file], newFileName)
        formData.append("file", newFile);
        formData.append('forceUpdate', '1');
        formData.append('path', 'm1/' + newFileName);
        this.$upload(this.apiURL.uploadCommonImg, formData)
          .then(r => {
            let data = r.data.data;
            if (r.data.code === 200) {
              let { id, fileName, filePath, fileType, absPath } = data;
              file.id = id;
              file.url = absPath;
              file.fileType = fileType;
              this.renderImageData[index].fileList.push(file);
              this.loading = false;
              this.$message.success("上传文件成功");
            }
          })
          .catch(r => {
            console.error(r);
            this.removeImageInFE(name, index, file);
            this.loading = false;
          });
      }
    },
    /**
     * @description: 阻止ant-design自带的自动上传事件
     * @return: false
     * @editor: youzi
     * @Date: 2019-09-17 11:32:38
     */
    beforeImageUpload(file, fileList) {
      this.loading = true;
      return false;
    },
    /**
     * @desc: 预览文件函数
     * @param {object} file
     * @author: youzi
     */
    handleImagePreview(file) {
      // console.warn(file);
      this.$download(this.apiURL.downloadFile + `?path=${file}`, {}, file);
      // this.$download(this.apiURL.downloadFile, { id: file.id }, file.name);
    },
    /**
     * 用于前端删除文件的函数
     * @param {string} name 文件所属的属性名
     * @param {number} index 属性名在渲染数组中所处的位置
     * @param {object} file 文件
     * @author: youzi
     * @Date: 2019-10-25 14:13:18
     */
    removeImageInFE(name, index, file) {
      let nowFileList = this.renderImageData[index].fileList;
      let fileIndex = -1;
      for (let i = 0; i < nowFileList.length; i++) {
        const el = nowFileList[i];
        if (el.uid === file.uid) {
          fileIndex = i;
          break;
        }
      }
      if (fileIndex === -1) {
        return;
      }
      const newFileList = this.renderImageData[index].fileList.slice();
      newFileList.splice(fileIndex, 1);
      this.renderImageData[index].fileList = newFileList;
      let key = this.renderImageData[index].dataIndex;
      this.form.setFieldsValue({ [key]: newFileList });
      // this.removeFile(file);
      this.$message.success("删除文件成功");
    },
    handleImageRemove(name, index, file) {
      if (file.status === "error") {
        // this.deleteFile(file);
        console.log("error");
        this.removeImageInFE(name, index, file);
        return;
      }
      // console.log('delete');
      this.$post(this.apiURL.deleteImage, { fileName: file.filenameEn })
        .then(r => {
          this.removeImageInFE(name, index, file);
        })
        .catch(r => {
          if (r.data.code === 10001) {
            this.removeImageInFE(name, index, file);
          }
          console.error(r);
        });
    }
  }
};
